import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../config/theme.dart';
import '../../generated/assets.dart';
import '../../utils/common/assets_utils.dart';
import 'svg_widget.dart';

extension ImageExtens on String {
  Widget showImage({
    double? width,
    double? height,
    BoxFit fit = BoxFit.contain,
    String? defImage,
  }) {
    return endsWith("svg")
        ? SvgWidget(this, width: width, height: height, fit: fit)
        : ImageX(
      this,
      width: width,
      height: height,
      fit: fit,
      errorImage: defImage,
    );
  }

  /// 监听加载图片
  void loadListener({ValueChanged<bool>? onResult}) {
    // 获取 ImageProvider
    final imageProvider = CachedNetworkImageProvider(this);
    // 解析图片并监听加载状态
    imageProvider.resolve(ImageConfiguration.empty).addListener(
      ImageStreamListener(
            (image, synchronousCall) {
          onResult?.call(true);
        },
        onError: (error, stackTrace) {
          onResult?.call(false);
        },
      ),
    );
  }
}

//封装图片加载控件，增加图片加载失败时加载默认图片
class ImageX extends StatelessWidget {
  final String url;
  final double? width;
  final double? height;
  final double? placeholderWidth;
  final double? placeholderHeight;
  final BoxFit fit;

  final String _errorImage;
  final String _placeholderImage;

  // 加载失败或者加载成功的回调
  final ValueChanged<bool>? onResult;

  const ImageX(
      this.url, {
        super.key,
        this.width,
        this.height,
        this.placeholderWidth,
        this.placeholderHeight,
        this.onResult,
        this.fit = BoxFit.cover,
        String? errorImage,
        String? placeholderImage,
      })  : _errorImage = errorImage ?? Assets.svgMaterialServiceError,
        _placeholderImage = placeholderImage ?? Assets.svgMaterialServiceError;

  @override
  Widget build(BuildContext context) {
    if (url.isEmpty) {
      return _getErrorWidget();
    }
    var urlResult = url;
    var isCallbackOk = false;
    if (url.startsWith("assets")) {
      final isDarkMode = ThemeUtils.isDark;
      urlResult = isDarkMode ? AssetsUtils.getDarkAssetPath(url) : url;
      return Image.asset(
        urlResult,
        width: width,
        height: height,
        fit: fit,
        frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
          if (frame != null && !isCallbackOk) {
            isCallbackOk = true;
            _callback(true);
          }
          return child;
        },
        errorBuilder: (context, error, stackTrace) {
          if (!isCallbackOk) {
            isCallbackOk = true;
            _callback(false);
          }
          return SizedBox.shrink();
        },
      );
    }
    return CachedNetworkImage(
      imageUrl: urlResult,
      width: width,
      height: height,
      fit: fit,
      placeholder: _placeholderImage.isEmpty
          ? null
          : (context, url) {
        return _getPlaceholderWidget();
      },
      imageBuilder: (context, imageProvider) {
        if (!isCallbackOk) {
          isCallbackOk = true;
          _callback(true);
        }
        return Image(
          image: imageProvider,
          width: width,
          height: height,
          fit: fit,
        );
      },
      errorWidget: (context, error, stackTrace) {
        stackTrace.printInfo();
        return _getErrorWidget();
      },
      errorListener: (error) {
        if (!isCallbackOk) {
          isCallbackOk = true;
          _callback(false);
        }
      },
    );
  }

  void _callback(bool isSuccess) {
    if (onResult != null) {
      // 延迟到当前帧结束后再更新状态
      WidgetsBinding.instance.addPostFrameCallback((_) {
        onResult!(isSuccess);
      });
    }
  }

  // 占位图
  Widget _getPlaceholderWidget() {
    if (_placeholderImage.isEmpty) {
      return const SizedBox.shrink();
    }
    if (_placeholderImage.startsWith("assets/svg")) {
      return SizedBox(
        width: width,
        height: height,
        child: Center(
            child: SvgWidget(
              _placeholderImage,
              width: placeholderWidth ?? width,
              height: placeholderHeight ?? height,
              fit: BoxFit.contain,
            )),
      );
    } else {
      return SizedBox(
        width: width,
        height: height,
        child: Center(
          child: Image.asset(
            _placeholderImage,
            width: placeholderWidth ?? width,
            height: placeholderHeight ?? height,
            fit: BoxFit.contain,
          ),
        ),
      );
    }
  }

  // 错误图
  Widget _getErrorWidget() {
    if (_errorImage.isEmpty) {
      return const SizedBox.shrink();
    }
    if (_errorImage.startsWith("assets/svg")) {
      return SizedBox(
        width: width,
        height: height,
        child: Center(
            child: SvgWidget(
              _errorImage,
              width: placeholderWidth ?? width,
              height: placeholderHeight ?? height,
              fit: BoxFit.contain,
            )),
      );
    } else {
      return SizedBox(
        width: width,
        height: height,
        child: Center(
          child: Image.asset(
            _errorImage,
            width: placeholderWidth ?? width,
            height: placeholderHeight ?? height,
            fit: BoxFit.contain,
          ),
        ),
      );
    }
  }
}
